<template>
  <div ref="chartRef" :style="{ height, width }"></div>
</template>
<script lang="ts" setup>
  import { onMounted, ref, Ref, watch } from 'vue';
  import { useECharts } from '@/hooks/web/useECharts';
  import { basicProps } from './props';
  import { useI18n } from '@/hooks/web/useI18n';

  const { t } = useI18n();
  const props = defineProps({
    ...basicProps,
    daylog: {
      type: [Array, Object],
      default: () => ({}),
    },
  });
  const chartRef = ref<HTMLDivElement | null>(null);
  const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);

  // 处理数据并设置图表选项
  const processDataAndSetOptions = () => {
    console.log('daylog data:', props.daylog);

    let dates: string[] = [];
    let values: number[] = [];

    // 尝试多种可能的数据结构
    try {
      // 结构1: daylog 直接是数组
      if (Array.isArray(props.daylog)) {
        if (
          props.daylog.length > 0 &&
          props.daylog[0].date &&
          props.daylog[0].value !== undefined
        ) {
          // 直接使用数组中的数据
          const last50Data = props.daylog.slice(-50);
          dates = last50Data.map((item: any) => item.date || '');
          values = last50Data.map((item: any) => item.value || 0);
        }
      }
      // 结构2: daylog.data.dayLogs 是数组
      else if (
        props.daylog &&
        typeof props.daylog === 'object' &&
        props.daylog.data &&
        Array.isArray(props.daylog.data.dayLogs)
      ) {
        const last50Data = props.daylog.data.dayLogs.slice(-50);
        dates = last50Data.map((item: any) => item.date || '');
        values = last50Data.map((item: any) => item.value || 0);
      }
      // 结构3: daylog 是对象，直接包含date和value字段
      else if (
        props.daylog &&
        typeof props.daylog === 'object' &&
        props.daylog.date &&
        props.daylog.value !== undefined
      ) {
        dates = [props.daylog.date];
        values = [props.daylog.value];
      }
    } catch (error) {
      console.error('Error processing chart data:', error);
    }

    // 即使没有数据也要显示空图表，避免白屏
    setOptions({
      grid: {
        top: 20, // 设置顶部距离
        left: 50, // 设置底部距离
        right: 50, // 设置底部距离
      },
      toolbox: {
        show: true,
        feature: {
          magicType: { show: true, type: ['line', 'bar'] },
        },
      },
      dataZoom: [
        {
          show: true,
          start: 0,
          end: 100,
        },
      ],
      xAxis: {
        type: 'category',
        data: dates.length > 0 ? dates : ['暂无数据'],
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          data: values.length > 0 ? values : [0],
          type: 'bar',
        },
      ],
      tooltip: {
        trigger: 'item',
        formatter: function (params: any) {
          return `${t('sys.device.columns.time')}: ${params.name}<br/>${t('sys.analysis.everynum')}: ${params.value}`;
        },
      },
    });
  };

  onMounted(() => {
    processDataAndSetOptions();
  });

  // 监听daylog变化，动态更新图表
  watch(
    () => props.daylog,
    () => {
      processDataAndSetOptions();
    },
    { deep: true },
  );
</script>
